package com.qs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qs.mapper.UserMapper;
import com.qs.pojo.dto.OnlineDto;
import com.qs.pojo.entity.Online;
import com.qs.mapper.OnlineMapper;
import com.qs.pojo.entity.User;
import com.qs.pojo.enums.LoginTypeStatus;
import com.qs.pojo.vo.OnlineVo;
import com.qs.service.IOnlineService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qs.utils.LoginTypeUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户在线状态表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-01-06
 */
@Service
@RequiredArgsConstructor
public class OnlineServiceImpl extends ServiceImpl<OnlineMapper, Online> implements IOnlineService {

    private final UserMapper userMapper;

    @Override
    public Map<String, Object> getOnlineList(Integer pageNo, Integer pageSize, OnlineVo onlineVo) {
        Page<Online> pageInfo = new Page<>(pageNo, pageSize);
        QueryWrapper<Online> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        if(onlineVo.getStatus() != null){
            wrapper.eq("status", onlineVo.getStatus());
        }
        Page<Online> onlinePage = baseMapper.selectPage(pageInfo, wrapper);
        if(null != onlinePage){
            List<Online> onlineList = onlinePage.getRecords();
            List<OnlineDto> list = new ArrayList<>();
            if(!CollectionUtils.isEmpty(onlineList)){
                onlineList.stream().forEach(online -> {
                    User user = userMapper.selectById(online.getUserId());
                    OnlineDto onlineDto = new OnlineDto();
                    onlineDto.setAvatar(user.getAvatar());
                    onlineDto.setUserName(user.getNickName());
                    onlineDto.setUserId(user.getId());
                    onlineDto.setId(online.getId());
                    onlineDto.setLoginType(online.getLoginType());
                    onlineDto.setStatus(online.getStatus().getStatus());
                    list.add(onlineDto);
                });
                if(!CollectionUtils.isEmpty(list)){
                    Map<String,Object> map = new HashMap<>();
                    map.put("data",list);
                    map.put("total",onlinePage.getTotal());
                    return map;
                }
            }
            return null;
        }
        return null;
    }
}
